package com.znufe.exam.service.impl;

import com.znufe.exam.domain.UserEventLog;
import com.znufe.exam.domain.other.KeyValue;
import com.znufe.exam.repository.UserEventLogMapper;
import com.znufe.exam.service.UserEventLogService;
import com.znufe.exam.utility.DateTimeUtil;
import com.znufe.exam.viewmodel.admin.user.UserEventPageRequestVM;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserEventLogServiceImpl extends BaseServiceImpl<UserEventLog> implements UserEventLogService {

    private final UserEventLogMapper userEventLogMapper;

    @Autowired
    public UserEventLogServiceImpl(UserEventLogMapper userEventLogMapper) {
        super(userEventLogMapper);
        this.userEventLogMapper = userEventLogMapper;
    }

    @Override
    public List<UserEventLog> getUserEventLogByUserId(Integer id) {
        return userEventLogMapper.getUserEventLogByUserId(id);
    }

    @Override
    public PageInfo<UserEventLog> page(UserEventPageRequestVM requestVM) {
        return PageHelper.startPage(requestVM.getPageNum(), requestVM.getPageSize(), "id desc").doSelectPageInfo(() ->
                userEventLogMapper.page(requestVM)
        );
    }


    @Override
    public List<Integer> selectMothCount() {
        Date startTime = DateTimeUtil.getMonthStartDay();
        Date endTime = DateTimeUtil.getMonthEndDay();
        List<KeyValue> mouthCount = userEventLogMapper.selectCountByDate(startTime, endTime);
        //[2020-05-01, 2020-05-02, 2020-05-03,...,2020-05-22]
        List<String> mothStartToNowFormat = DateTimeUtil.MothStartToNowFormat();
        //Java流(Stream)
        //取出对应日期的访问人数
        //[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        return mothStartToNowFormat.stream().map(md -> {
            KeyValue keyValue = mouthCount.stream()
                                            .filter(kv -> kv.getName()
                                            .equals(md))
                                            .findAny()
                                            .orElse(null);
            //keyValue是否为null，如果是则返回0，不是则返回keyValue.getValue()
            return null == keyValue ? 0 : keyValue.getValue();
        }).collect(Collectors.toList());

    }

}
